import { BrowserWindow, shell, Menu } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import icon from '../../../resources/logo.png?asset'
import { AppInfo } from '../config/app-info'
import { AppConfig } from '../config/app'

// 导入日志
import mainLogger from '../logger'

/**
 * 创建主窗口
 */
export function createMainWindow(): BrowserWindow {
  // Create the browser window.
  const windowTitle = AppInfo.getWindowTitle()
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    icon: icon,
    title: windowTitle,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      // 生产环境禁用开发者工具
      devTools: AppConfig.FEATURES.DEV_TOOLS,
      // 🔒 安全配置（必须）
      nodeIntegration: AppConfig.SECURITY.NODE_INTEGRATION,
      contextIsolation: AppConfig.SECURITY.CONTEXT_ISOLATION,
      webSecurity: AppConfig.SECURITY.WEB_SECURITY,
      allowRunningInsecureContent: AppConfig.SECURITY.ALLOW_INSECURE_CONTENT,
      experimentalFeatures: false // 禁用实验性功能
    }
  })

  // 完全禁用菜单栏（防止 Alt 键显示菜单）
  if (!is.dev) {
    Menu.setApplicationMenu(null)
  }

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
    // 确保标题正确设置
    mainWindow.setTitle(windowTitle)
    mainLogger.info('窗口显示后设置标题', { windowTitle })
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  return mainWindow
}

/**
 * 窗口控制操作
 */
export class WindowController {
  /**
   * 获取主窗口
   */
  static getMainWindow(): BrowserWindow | null {
    const windows = BrowserWindow.getAllWindows()
    return windows.length > 0 ? windows[0] : null
  }

  /**
   * 最小化窗口
   */
  static minimize(): void {
    const focusedWindow = BrowserWindow.getFocusedWindow()
    if (focusedWindow) {
      focusedWindow.minimize()
    }
  }

  /**
   * 最大化/还原窗口
   */
  static toggleMaximize(): void {
    const focusedWindow = BrowserWindow.getFocusedWindow()
    if (focusedWindow) {
      if (focusedWindow.isMaximized()) {
        focusedWindow.unmaximize()
      } else {
        focusedWindow.maximize()
      }
    }
  }

  /**
   * 设置全屏状态
   */
  static setFullScreen(fullscreen: boolean): void {
    const focusedWindow = BrowserWindow.getFocusedWindow()
    if (focusedWindow) {
      focusedWindow.setFullScreen(fullscreen)
    }
  }
}
